package org.gesplan.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.gesplan.entity.Location;
import org.gesplan.entity.LocationGroup;
import org.gesplan.exceptions.NonexistentEntityException;
import org.gesplan.exceptions.PreexistingEntityException;


/**
 *
 * @author Roger
 */
public class LocationGroupJpaController {

    public LocationGroupJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }
    

    public void create(LocationGroup locationGroup) throws PreexistingEntityException, Exception {
        
        if (locationGroup.getLocationCollection() == null) {
            locationGroup.setLocationCollection(new ArrayList<Location>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Location> attachedLocationCollection = new ArrayList<>();
            for (Location locationCollectionLocationToAttach : locationGroup.getLocationCollection()) {
                locationCollectionLocationToAttach = em.getReference(locationCollectionLocationToAttach.getClass(), locationCollectionLocationToAttach.getId());
                attachedLocationCollection.add(locationCollectionLocationToAttach);
            }
            locationGroup.setLocationCollection(attachedLocationCollection);
            em.persist(locationGroup);
            for (Location locationCollectionLocation : locationGroup.getLocationCollection()) {
                LocationGroup oldLocationGroupIdOfLocationCollectionLocation = locationCollectionLocation.getLocationGroupId();
                locationCollectionLocation.setLocationGroupId(locationGroup);
                locationCollectionLocation = em.merge(locationCollectionLocation);
                if (oldLocationGroupIdOfLocationCollectionLocation != null) {
                    oldLocationGroupIdOfLocationCollectionLocation.getLocationCollection().remove(locationCollectionLocation);
                    em.merge(oldLocationGroupIdOfLocationCollectionLocation);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findLocationGroup(locationGroup.getId()) != null) {
                throw new PreexistingEntityException("LocationGroup " + locationGroup + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }

    
    public void edit(LocationGroup locationGroup) throws NonexistentEntityException, Exception {
    	
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            LocationGroup persistentLocationGroup = em.find(LocationGroup.class, locationGroup.getId());
            Collection<Location> locationCollectionOld = persistentLocationGroup.getLocationCollection();
            Collection<Location> locationCollectionNew = locationGroup.getLocationCollection();
            Collection<Location> attachedLocationCollectionNew = new ArrayList<>();
            for (Location locationCollectionNewLocationToAttach : locationCollectionNew) {
                locationCollectionNewLocationToAttach = em.getReference(locationCollectionNewLocationToAttach.getClass(), locationCollectionNewLocationToAttach.getId());
                attachedLocationCollectionNew.add(locationCollectionNewLocationToAttach);
            }
            locationCollectionNew = attachedLocationCollectionNew;
            locationGroup.setLocationCollection(locationCollectionNew);
            locationGroup = em.merge(locationGroup);
            for (Location locationCollectionOldLocation : locationCollectionOld) {
                if (!locationCollectionNew.contains(locationCollectionOldLocation)) {
                    locationCollectionOldLocation.setLocationGroupId(null);
                    locationCollectionOldLocation = em.merge(locationCollectionOldLocation);
                }
            }
            for (Location locationCollectionNewLocation : locationCollectionNew) {
                if (!locationCollectionOld.contains(locationCollectionNewLocation)) {
                    LocationGroup oldLocationGroupIdOfLocationCollectionNewLocation = locationCollectionNewLocation.getLocationGroupId();
                    locationCollectionNewLocation.setLocationGroupId(locationGroup);
                    locationCollectionNewLocation = em.merge(locationCollectionNewLocation);
                    if (oldLocationGroupIdOfLocationCollectionNewLocation != null && !oldLocationGroupIdOfLocationCollectionNewLocation.equals(locationGroup)) {
                        oldLocationGroupIdOfLocationCollectionNewLocation.getLocationCollection().remove(locationCollectionNewLocation);
                        em.merge(oldLocationGroupIdOfLocationCollectionNewLocation);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Short id = locationGroup.getId();
                if (findLocationGroup(id) == null) {
                    throw new NonexistentEntityException("The locationGroup with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }

    
    public void destroy(Short id) throws NonexistentEntityException {
        
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            LocationGroup locationGroup;
            try {
                locationGroup = em.getReference(LocationGroup.class, id);
                locationGroup.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The locationGroup with id " + id + " no longer exists.", enfe);
            }
            Collection<Location> locationCollection = locationGroup.getLocationCollection();
            for (Location locationCollectionLocation : locationCollection) {
                locationCollectionLocation.setLocationGroupId(null);
                locationCollectionLocation = em.merge(locationCollectionLocation);
            }
            em.remove(locationGroup);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }

    
    public List<LocationGroup> findLocationGroupEntities() {
        return findLocationGroupEntities(true, -1, -1);
    }

    public List<LocationGroup> findLocationGroupEntities(int maxResults, int firstResult) {
        return findLocationGroupEntities(false, maxResults, firstResult);
    }

    
    @SuppressWarnings({ "rawtypes", "unchecked" })    
    private List<LocationGroup> findLocationGroupEntities(boolean all, int maxResults, int firstResult) {
        
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(LocationGroup.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
        
    }

    
    public LocationGroup findLocationGroup(Short id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(LocationGroup.class, id);
        } finally {
            em.close();
        }
    }

    
    @SuppressWarnings({ "rawtypes", "unchecked" })    
    public int getLocationGroupCount() {
        
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<LocationGroup> rt = cq.from(LocationGroup.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
        
    }
    
    
}